$(document).ready(function(){
	var canvas = document.getElementById("myCanvas");
	var templateList = document.getElementById("templateList");
	var context = canvas.getContext("2d");
	var ColorP = document.getElementById('panel');
    var ColorPctx = ColorP.getContext('2d');
    var CurrentColor = "#010101";
    var image ='ColorGuy.jpg';
	var myObjects = new Array();
	var redoObjects = new Array();
	var templates = new Array();
	var drawing = false;
	var mouseDown = false;
	var rec = false;
	var cir = false;
	var lin = false;
	var fre = true;
	var tex = false;
	var selectShape = false;
	var texting = false;
	var textx = 0;
	var texty = 0;
	var x = 0;
	var y = 0;
	var oldX = 0;
	var oldY = 0;
	
	function deSelect(){
		cir = false;
		rec = false;
		lin = false;
		fre = false;
		tex = false;
		selectShape = false;
		for(var index = 0; index<myObjects.length;index++){
			myObjects[index].deSelect();
		}
	}
	
	$("#circle").mousedown(function(e){
		deSelect();
		console.log("circle");
		cir=true;        	
	});
	
	$("#rectangle").mousedown(function(e){
		deSelect();
		console.log("rectangle");
		rec=true;        	
	});
	
	$("#line").mousedown(function(e){
		deSelect();
		console.log("line");
		lin=true;        	
	});
	
	$("#freehand").mousedown(function(e){ 
		deSelect();
		console.log("Pen");
		fre = true;
	});
	$("#selectShape").mousedown(function(e){
		deSelect();
		console.log("Select");
		selectShape = true;
	});
	$("#undo").mousedown(function(e){
		if(myObjects.length >0){
			redoObjects.push(myObjects.pop());
			reDraw();
			console.log("undo");
		}
	});
	$("#redo").mousedown(function(e){
		if(redoObjects.length>0){
			myObjects.push(redoObjects.pop());
			reDraw();
			console.log("Redo");
		}
	});
	$("#text").mousedown(function(e){
			deSelect();
			console.log("Text");
			tex = true;
	});
	$("#template").mousedown(function(e){
		if(myObjects.length>0){
			templateList.length=0;
			var t = new template();
			t.setName(document.getElementById("templateName").value);
			for(var i = 0; i<myObjects.length;i++)
			{
				var newObject = jQuery.extend(true, {}, myObjects[i]);
				t.addShape(newObject);
			}
			templates.push(t);
			if(templates.length === 1){
				templateList.length=0;
			}

			for(index in templates){
                templateList.options[templateList.options.length] = new Option(templates[index].getName(),index);
            }
		}
	});
	$("#addTemplate").mousedown(function(e){
		if(templates.length>0){
			var index = document.getElementById("templateList").value;
			var newObject = jQuery.extend(true, {}, templates[index]);
			myObjects.push(newObject);
			reDraw();
			//console.log(document.getElementById("templateList").value);
		}
	});
			
				
	$("#myCanvas").mousedown(function(e){
		mouseDown = true;
		x = e.pageX - this.offsetLeft;
		y = e.pageY - this.offsetTop;
		if(selectShape){
			//ath með að selecta mörg, þetta deselectar allt
			for(var index = 0; index<myObjects.length;index++){
				myObjects[index].deSelect();
			}
			for(var index = myObjects.length-1; index>=0;index--){
				if(myObjects[index].checkCollision(x,y)){
					myObjects[index].select();
					break;
				}
			}
		}
		else if(tex && !texting){
				console.log("test");
				textx = x + $("#myCanvas").position().left;
				texty = y + $("#myCanvas").position().top;
				var textArea = "<div id='textAreaPopUp' style='position:absolute;top:"+texty+"px;left:"+textx+"px;z-index:30;'><textarea id='insertText' style='width:300px;height:50px;border-style:solid;font-size:30px;font-style:Arial;'></textarea>";
				var appendString = textArea;
				$("#theCanvas").append(appendString);
				texting = true;
		}
		else{
			
			if(rec){
				object = new rectangle(context,x,y,0,0,CurrentColor);
			}
			else if(cir){
				object = new circle(context,x,y,0,CurrentColor);
			}
			else if(lin){
				object = new line(context,x,y,x,y,CurrentColor);
			}
			else if(fre){
				object = new freehand(context,x,y,CurrentColor);
			}
			object.draw();
			myObjects.push(object);
			console.log(myObjects);
			drawing = true;

		}
		
	});
	$("#saveButton").mousedown(function(e){
		document.getElementById("saveText").value = "";
		for(var i = 0; i<myObjects.length;i++){
			document.getElementById("saveText").value +=myObjects[i].getDescription()+'\n';
		}
	});	
	$("#loadButton").mousedown(function(e){
		var text = document.getElementById("saveText").value;
		var line = text.split('\n');
		for(var i = 0; i<line.length;i++){
			var cmd = line[i].split(":");
			if(cmd[0] === "0"){
				myObjects.push(loadRectangle(cmd[1],cmd[2],cmd[3],cmd[4]));
			};
			if(cmd[0] === "1"){
				myObjects.push(loadCircle(cmd[1],cmd[2],cmd[3]));
			};
			if(cmd[0] === "2"){
				myObjects.push(loadLine(cmd[1],cmd[2],cmd[3],cmd[4]));
			};
			if(cmd[0] === "3"){
				myObjects.push(loadFreehand(cmd));
			}
			if(cmd[0] === "4"){
				var t = new template();
				myObjects.push(t);
				var templateCmd = line[i].split("X");
				for(var k = 0; k<templateCmd.length;k++){
					var tmp = templateCmd[k].split(":");
					for(var j = 1; j<tmp.length;j++){
						if(tmp[0] === "0"){
							t.addShape(loadRectangle(tmp[1],tmp[2],tmp[3],tmp[4]));
						}
						if(tmp[0] === "1"){
							t.addShape(loadCircle(tmp[1],tmp[2],tmp[3]));
						};
						if(tmp[0] === "2"){
							t.addShape(loadLine(tmp[1],tmp[2],tmp[3],tmp[4]));
						};
						if(tmp[0] === "3"){
							t.addShape(loadFreehand(tmp));
						}

					}
				}
				
			}	
			//drawing = true;
		}
		
	});
	function loadRectangle(x,y,width,height){
		var s = new rectangle(context,x,y,width,height);
		s.draw();
		return s;
	}
	function loadCircle(x,y,rad){
		var s = new  circle(context,x,y,rad)
		s.draw();
		return s;
	}
	function loadLine(x,y,x2,y2){
		var s = new new line(cmd[1],cmd[2],cmd[3],cmd[4]);
		s.draw();
		return s;
	}
	function loadFreehand(arr){
		var s = new freehand(context,arr[3],arr[4]);
		for(var k =1; k<arr.length;k+=2){
			s.add(arr[k],arr[k+1]);
		}
		s.draw();
		return s;
	}

	$("#myCanvas").mousemove(function(e){
		var newX = e.pageX - this.offsetLeft;
		var newY = e.pageY - this.offsetTop;
		if(drawing){
		
			if(fre){
				myObjects[(myObjects.length - 1)].add(newX,newY);
			}
			else{
				myObjects[(myObjects.length - 1)] = myObjects[(myObjects.length - 1)].reDraw(newX,newY);
			}
	
			//context.clearRect(0, 0, canvas.width, canvas.height);
			for (var i = 0;i < myObjects.length; i++){
				myObjects[i].draw();
			}
		}
		if(mouseDown){
			for(var index = 0; index<myObjects.length;index++){
				if(myObjects[index].isSelected()){
				console.log(newX+","+newY);
					myObjects[index].translate(newX-x,newY-y);


				}
				
			}
			reDraw();
		}
	});
	
	$("#myCanvas").mouseup(function(e){
		drawing = false;
		if(mouseDown){
			mouseDown = false;
			for(var index = 0; index<myObjects.length;index++){
				if(myObjects[index].isSelected()){
					myObjects[index].setPosition();
				}
			}
		}

	});
	
	$("#all").keydown(function(e){
		if(texting && e.keyCode == 13){
			mouseDown = false;
			var textVal = $("textarea#insertText").val();
			console.log(textVal);
			$("textarea#insertText").remove();
			$("#textAreaPopUp").remove();
			texting = false;
			if(textVal.indexOf("$pi")!= -1){
				console.log(textVal.indexOf("$pi"));
				textVal = textVal.replace("$pi",String.fromCharCode(226));
			}
			var object = new text(context,textVal,x,y+20,CurrentColor);
			object.draw();
			myObjects.push(object);
			
		}
	});
	


	function reDraw()
	{
		context.clearRect(0, 0, canvas.width, canvas.height);
		for (var i = 0;i < myObjects.length; i++){
			myObjects[i].draw();
		}
	}
	var image = new Image();
	$('#selectedColor').css('backgroundColor', CurrentColor);
	image.src = 'ColorGuy.jpg';
	image.width="400";
    image.height="250";
    image.onload = function () {
        ColorPctx.drawImage(image, 0, 0, image.width, image.height); // draw the image on the canvas
    }
  

	   $('#panel').mousemove(function(e) {
        var canvasOffset = $(ColorP).offset();
        var canvasX = Math.floor(e.pageX - canvasOffset.left);
        var canvasY = Math.floor(e.pageY - canvasOffset.top);

        var imageData = ColorPctx.getImageData(canvasX, canvasY, 1, 1);
        var pixel = imageData.data;

        var pixelColor = "rgba("+pixel[0]+", "+pixel[1]+", "+pixel[2]+", "+pixel[3]+")";
        $('#preview').css('backgroundColor', pixelColor);
    });

    $('#panel').click(function(e) { 
        var canvasOffset = $(ColorP).offset();
        var canvasX = Math.floor(e.pageX - canvasOffset.left);
        var canvasY = Math.floor(e.pageY - canvasOffset.top);

        var imageData = ColorPctx.getImageData(canvasX, canvasY, 1, 1);
        var pixel = imageData.data;

        $('#rVal').val(pixel[0]);
        $('#gVal').val(pixel[1]);
        $('#bVal').val(pixel[2]);

        $('#rgbVal').val(pixel[0]+','+pixel[1]+','+pixel[2]);
        $('#rgbaVal').val(pixel[0]+','+pixel[1]+','+pixel[2]+','+pixel[3]);
        var dColor = pixel[2] + 256 * pixel[1] + 65536 * pixel[0];
        $('#hexVal').val( '#' + dColor.toString(16) );
        CurrentColor = '#' + dColor.toString(16);
        $('#selectedColor').css('backgroundColor', CurrentColor);
    }); 


});
